package cn.edu.stu.syllabus.repository.library;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import cn.edu.stu.syllabus.repository.library.local.BookEntry;
import cn.edu.stu.syllabus.repository.library.local.BooksResultEntry;

/**
 * Created by daidaijie on 2017/3/27.
 */

public class BookConverter {

    private static final String LIBRARY_URL = "http://opac.lib.stu.edu.cn:83/opac/";

    private static final String BOOK_URL = "http://opac.lib.stu.edu.cn:83/opac/bookinfo.aspx?ctrlno=";


    public static BooksResultEntry convert(String htmlString) {

        BooksResultEntry booksResultEntry = new BooksResultEntry();

        List<BookEntry> bookEntries = new ArrayList<>();

        Element body = Jsoup.parseBodyFragment(htmlString).body();

        Element countString = body.select("span#ctl00_ContentPlaceHolder1_countlbl").first();

        try {
            booksResultEntry.searchNum = Long.parseLong(countString.text().trim());
        } catch (NumberFormatException numberFormatException) {
            booksResultEntry.searchNum = 0;
        }

        Element table = body.select("table.tb").first();
        Elements items = table.getElementsByTag("tr");
        items.remove(0);

        for (Element item : items) {
            BookEntry bookEntry = new BookEntry();

            Elements tdItem = item.getElementsByTag("td");

            Element href = tdItem.get(1).getElementsByTag("span").first().getElementsByTag("a").first();
            bookEntry.setUrl(LIBRARY_URL + href.attr("href"));
            bookEntry.setRemoteId(Long.parseLong(bookEntry.getUrl().substring(
                    BOOK_URL.length(), bookEntry.getUrl().length()
            )));

            bookEntry.setName(tdItem.get(1).text());
            bookEntry.setAuthor(tdItem.get(2).text());
            bookEntry.setPress(tdItem.get(3).text());
            bookEntry.setPressDate(tdItem.get(4).text());
            try {
                bookEntry.setInLibraryNum(Integer.parseInt(tdItem.get(7).text()));
                bookEntry.setSumNum(Integer.parseInt(tdItem.get(6).text()));
            } catch (NumberFormatException e) {
                bookEntry.setSumNum(0);
                bookEntry.setInLibraryNum(0);
            }
            bookEntries.add(bookEntry);
        }
        booksResultEntry.bookEntries = bookEntries;

        return booksResultEntry;
    }
}
